﻿using EM.FrameWork.Paging;
using EM.OA.BLL;
using EM.OA.DataModel.DBModel;
using EM.OA.Portal.Models;
using EM.OA.WebCommon;
using EM.OA.WebCommon.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EM.OA.Portal.Controllers
{
    public class WFApplyController : BaseAuthController
    {
        /// <summary>
        /// 返回Index视图
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //ViewBag.UserName = this.CurrentUser.UserName;
            ViewBag.UserName = CurrentUser.UserName;
            ViewBag.OUName = "联想安全";
            return View();
        }

        /// <summary>
        /// 我的申请
        /// </summary>
        /// <returns></returns>
        public ActionResult WorkFlow()
        {
            ViewBag.UserID = CurrentUser.UserID;

            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public JsonResult GetList(string page, string rows)
        {
            List<object> result = new List<object>();
            WFApplyBLL bll = new WFApplyBLL();
            EMOA_WF_Apply model = new EMOA_WF_Apply();
            string _flowKind = GetParam("j_flowKind");
            string _status = GetParam("j_status");
            string _applyUserID = string.Empty;
            string _approvalUserID = string.Empty;

            if (!string.IsNullOrEmpty(GetParam("j_isapproval")))
            {
                if (bool.Parse(GetParam("j_isapproval")))//我的审批，给审批人赋值
                    _approvalUserID = GetParam("j_userID");
                else
                    _applyUserID = GetParam("j_userID");//我的申请，给申请人赋值
            }
            if (!string.IsNullOrEmpty(_flowKind))
                model.FlowKind = Guid.Parse(_flowKind);
            if (!string.IsNullOrEmpty(_status))
                model.Status = byte.Parse(_status);
            if (!string.IsNullOrEmpty(_applyUserID))
                model.ApplyUserID = Guid.Parse(_applyUserID);
            if (!string.IsNullOrEmpty(_approvalUserID))
                model.NextApprovalUserID = Guid.Parse(_approvalUserID);
            PagedList<EMOA_WF_Apply> list = bll.GetApplyList(model, new PageEntity() { PageIndex = Convert.ToInt32(page), PageSize = Convert.ToInt32(rows) });

            list.ForEach(p =>
            {
                result.Add(new WFApplyModels().ToModel(p));
            });

            return ToJson(result, list.TotalItemCount);
        }

        /// <summary>
        /// 获取改流程的步骤明细
        /// </summary>
        /// <returns></returns>
        public JsonResult GetApprovallist()
        {
            Guid _applyID = new Guid(GetParam("applyID"));
            List<EMOA_WF_Approval> list = new List<EMOA_WF_Approval>();
            list = new WFApprovalBLL().GetApprovallist(_applyID);

            List<object> result = new List<object>();
            list.ForEach(p => {
                result.Add(new WFApprovalModels().ToModel(p));
            });

            return ToJson(result,list.Count());
        }

        /// <summary>
        /// 增加实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(WFApplyModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    WFApplyBLL bll = new WFApplyBLL();
                    EMOA_WF_Apply entity = model.ToEntity<EMOA_WF_Apply>();
                    entity.ApplyID = Guid.NewGuid();
                    entity.CreateBy = CurrentUser.UserID;
                    entity.CreateTime = DateTime.Now;
                    entity.ApplyUserID = CurrentUser.UserID;
                    entity.ApplyDepartmentID = new Guid();//需要改

                    EMOA_WF_Approval approval = new EMOA_WF_Approval();
                    approval.ApprovalID = Guid.NewGuid();
                    approval.ApplyID = entity.ApplyID;

                    EMOA_WF_FlowConfig config = new WFFlowConfigBLL().GetEntity(model.ApplyFlowConfigID.Value);
                    approval.FlowConfigDetailID = new WFFlowConfigDetailBLL().GetList(p => p.FlowConfigID == config.FlowConfigID).OrderBy(p => p.StepLevel).FirstOrDefault().FlowConfigDetailID;
                    approval.ApprovalUserID = model.ApprovalUserID;
                    approval.Status = 1;//已开始
                    approval.CreateTime = DateTime.Now;
                    approval.CreateBy = this.CurrentUser.UserID;
                    WFApprovalBLL approvalBll = new WFApprovalBLL();
                    if (bll.Add(entity) && approvalBll.Add(approval))
                    {
                        return Content("OK");
                    }
                    else
                    {
                        return Content("增加失败");
                    }
                }
                else
                    return Content("验证失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(WFApplyModels model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    EMOA_WF_Approval approvalEntity = new EMOA_WF_Approval();
                    EMOA_WF_Approval oldapprovalEntity = new EMOA_WF_Approval();

                    oldapprovalEntity = new WFApprovalBLL().GetEntity(model.NowApprovalID.Value);
                    oldapprovalEntity.AprovalRemark = model.AprovalRemark;
                    oldapprovalEntity.IsEmail = model.IsEmail;
                    oldapprovalEntity.IsSMS = model.IsSMS;
                    oldapprovalEntity.IsWebMessage = model.IsWebMessage;
                    oldapprovalEntity.ApprovalDate = DateTime.Now;
                    oldapprovalEntity.UpdateBy = CurrentUser.UserID;
                    oldapprovalEntity.UpdateTime = DateTime.Now;

                    if (model.ApprovalStatus.Value == 2)
                    {
                        //流程通过，进行下一步
                        //1.判断流程是否结束（是否有下一步审核步骤）,如果没有，往EMOA_WF_Approval中插入一条新记录,如果流程结束,修改EMOA_WF_Apply他的状态,;
                        //2.修改原来的EMOA_WF_Approval状态为通过;

                        oldapprovalEntity.Status = 2;

                        if (model.NextFlowConfigDetailID.HasValue && model.NextFlowConfigDetailID.Value != new Guid())
                        {
                            approvalEntity.ApprovalID = Guid.NewGuid();
                            approvalEntity.ApplyID = model.ApplyID;
                            approvalEntity.FlowConfigDetailID = model.NextFlowConfigDetailID.Value;

                            approvalEntity.ApprovalUserID = model.NextApprovalUserID.Value;

                            approvalEntity.AprovalRemark = model.AprovalRemark;
                            approvalEntity.Status = 1;

                            approvalEntity.IsEmail = model.IsEmail;
                            approvalEntity.IsSMS = model.IsSMS;
                            approvalEntity.IsWebMessage = model.IsWebMessage;
                            approvalEntity.HaveAttachment = model.HaveAttachment;
                            
                            approvalEntity.CreateBy = CurrentUser.UserID;
                            approvalEntity.CreateTime = DateTime.Now;

                            if (new WFApprovalBLL().Add(approvalEntity) && new WFApprovalBLL().Update(oldapprovalEntity))
                                return Content("OK");
                            else
                                return Content("保存失败");

                        }
                        else
                        {
                            EMOA_WF_Apply applyEntity = new EMOA_WF_Apply();
                            applyEntity = new WFApplyBLL().GetEntity(model.ApplyID.Value);
                            applyEntity.Status = 1;


                            oldapprovalEntity.Status = 4;
                            if (new WFApprovalBLL().Update(oldapprovalEntity) && new WFApplyBLL().Update(applyEntity))
                                return Content("OK");
                            else
                                return Content("保存失败");

                        }
                    }
                    else
                    {
                        oldapprovalEntity.Status = model.ApprovalStatus;
                        if (new WFApprovalBLL().Update(oldapprovalEntity))
                            return Content("OK");
                        else
                            return Content("失败");
                    }

                    
                }
                else
                    return Content("验证失败");

            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

        /// <summary>
        /// 删除实体
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(string id)
        {
            try
            {
                WFApplyBLL bll = new WFApplyBLL();
                if (bll.Delete(Guid.Parse(id)))
                    return Content("OK");
                else
                    return Content("删除失败");
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }

    }
}